import 'dart:async';

import 'package:flukit/flukit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:stage_app/constants/color_constant.dart';
import 'package:stage_app/constants/constant.dart';
import 'package:stage_app/utils/date_util.dart';
import 'package:stage_app/utils/security_util.dart';
import 'package:stage_app/wigets/button/round_button.dart';
import 'package:stage_app/wigets/common/number_text_field.dart';

class OrderPage extends StatefulWidget {
  @override
  createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage>
    with SingleTickerProviderStateMixin {
  int _current = 0;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  String _startDate = DateUtil.format(pattern: DateUtil.DATE_PATTERN);
  String _endDate = DateUtil.format(pattern: DateUtil.DATE_PATTERN);
  String _printStatus = '全部';
  String _smsStatus = '全部';

  Future<void> _selectStartDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: DateUtil.parse(_startDate, pattern: DateUtil.DATE_PATTERN),
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != _startDate) {
      print(
          "data selectied :${DateUtil.format(date: picked, pattern: DateUtil.DATE_PATTERN)}");
    }
    setState(() {
      _startDate =
          DateUtil.format(date: picked, pattern: DateUtil.DATE_PATTERN);
    });

    if (picked == null) {
      _startDate = DateUtil.format(pattern: DateUtil.DATE_PATTERN);
    }
  }

  Future<void> _selectEndDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: DateUtil.parse(_endDate, pattern: DateUtil.DATE_PATTERN),
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != _endDate) {
      print(
          "data selectied :${DateUtil.format(date: picked, pattern: DateUtil.DATE_PATTERN)}");
    }
    setState(() {
      _endDate = DateUtil.format(date: picked, pattern: DateUtil.DATE_PATTERN);
    });

    if (picked == null) {
      _endDate = DateUtil.format(pattern: DateUtil.DATE_PATTERN);
    }
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: ColorConstant.app_bg,
      appBar: AppBar(
        title:
            Text('寄件订单', style: new TextStyle(color: ColorConstant.text_dark)),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0, //设置阴影辐射范围
      ),
      body: Container(
//          margin: EdgeInsets.symmetric(horizontal: SizeConstants.marginSize.w),
        child: Column(
          children: <Widget>[
            topBar(),
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(
                    horizontal: SizeConstants.marginSize.w),
                child: buildListView(),
              ),
            )
          ],
        ),
      ),
//      drawerEdgeDragWidth: 0.0, // 禁止手势侧滑出Drawer
      endDrawer: Drawer(
        child: Container(
          child: Stack(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(
                    left: SizeConstants.marginSize,
                    right: SizeConstants.marginSize,
                    top: SizeConstants.marginSize),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: statusBarHeight,
                    ),
                    GestureDetector(
                      child: Padding(
                        padding: EdgeInsets.all(0),
                        child: Icon(Icons.close),
                      ),
                      onTap: () {
                        handleCloseDrawer();
                      },
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 20.0.w),
                      child: Text('时间段'),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 20.0.w),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: GestureDetector(
                              child: Container(
                                alignment: Alignment.center,
                                padding: EdgeInsets.symmetric(vertical: 10.0.w),
                                color: ColorConstant.gray_f0,
                                child: Text(_startDate),
                              ),
                              onTap: () {
                                _selectStartDate(context);
                              },
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 12.5.w),
                            child: Text('-'),
                          ),
                          Expanded(
                            child: GestureDetector(
                              child: Container(
                                alignment: Alignment.center,
                                padding: EdgeInsets.symmetric(vertical: 10.0.w),
                                color: ColorConstant.gray_f0,
                                child: Text(_endDate),
                              ),
                              onTap: () {
                                _selectEndDate(context);
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 20.0.w),
                      child: Text('打印状态'),
                    ),
                    SizedBox(height: 20.h,),
                    Container(
                      height: 47.h,
                      color: ColorConstant.gray_f0,
                      padding: EdgeInsets.symmetric(horizontal: 15.5.w),
                      child: DropdownButtonHideUnderline(
                        child: DropdownButton<String>(
                          isExpanded: true,
                          value: _printStatus,
                          style: TextStyle(
                              fontSize: 12.sp, color: ColorConstant.text_dark),
                          onChanged: (String newValue) {
                            setState(() {
                              _printStatus = newValue;
                            });
                          },
                          items: <String>[
                            '全部',
                            '已打印',
                            '未打印',
                          ].map<DropdownMenuItem<String>>((String value) {
                            return DropdownMenuItem<String>(
                              value: value,
                              child: Text(value),
                            );
                          }).toList(),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 20.0.w),
                      child: Text('短信状态'),
                    ),
                    SizedBox(height: 20.h,),
                    Container(
                      height: 47.h,
                      color: ColorConstant.gray_f0,
                      padding: EdgeInsets.symmetric(horizontal: 15.5.w),
                      child: DropdownButtonHideUnderline(
                        child: DropdownButton<String>(
                          isExpanded: true,
                          value: _smsStatus,
                          style: TextStyle(
                              fontSize: 12.sp, color: ColorConstant.text_dark),
                          onChanged: (String newValue) {
                            setState(() {
                              _smsStatus = newValue;
                            });
                          },
                          items: <String>[
                            '全部',
                            '已发送',
                            '未发送',
                          ].map<DropdownMenuItem<String>>((String value) {
                            return DropdownMenuItem<String>(
                              value: value,
                              child: Text(value),
                            );
                          }).toList(),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            border: Border(
                                top: BorderSide(
                                    width: 0.5, color: ColorConstant.gray_f0))),
                        child: RoundButton(
                          text: '重置',
                          style: TextStyle(fontSize: 15.sp),
                          radius: 0,
                          bgColor: Colors.white,
                          onPressed: () {
                            resetFilter();
                          },
                        ),
                      ),
                    ),
                    Expanded(
                      child: RoundButton(
                        text: '确定完成',
                        style: TextStyle(fontSize: 15.sp, color: Colors.white),
                        radius: 0,
                        bgColor: ColorConstant.app_main,
                        onPressed: () {},
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  buildListView() {
    return InfiniteListView<int>(
//      headerBuilder: (list, context) {
//        return Padding(
//          padding: EdgeInsets.all(16.0),
//          child: Text("功能介绍: 支持下拉刷新和上拉加载"),
//        );
//      },
      itemBuilder: (List list, int index, BuildContext ctx) {
        return buildListItem(list, index, ctx);
      },
      onRetrieveData: (int page, List items, bool refresh) {
        return Future.delayed(Duration(seconds: 2), () {
          int start = _current;
          if (refresh) {
            //如果是下拉数显
            _current = start = 0;
            items.clear();
          }
          if (_current == 50) return false; //最多加载50条
          while (start++ < _current + 10) {
            items.add(start);
          }
          _current += 10;
          return true;
        });
      },
      loadingBuilder: (context) {
        return Padding(
          padding: EdgeInsets.all(8.0.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              AnimatedRotationBox(
                duration: Duration(milliseconds: 800),
                child: GradientCircularProgressIndicator(
                  radius: 10.0,
                  colors: [Colors.blue, Colors.lightBlue[50]],
                  value: .8,
                  backgroundColor: Colors.transparent,
                  strokeCapRound: true,
                ),
              ),
              Text("  加载更多...")
            ],
          ),
        );
      },
      noMoreViewBuilder: (list, context) {
        return Center(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(
              "共${list.length}条",
              style: TextStyle(color: Colors.grey),
            ),
          ),
        );
      },
    );
  }

  topBar() {
    return Container(
      margin: EdgeInsets.only(top: 4.0.w),
      padding: EdgeInsets.symmetric(
          vertical: 13.0.w, horizontal: SizeConstants.marginSize.w),
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '订单列表',
            style: TextStyle(fontSize: 11.5.sp),
          ),
          GestureDetector(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text(
                  '筛选',
                  style: TextStyle(fontSize: 11.5.sp),
                ),
                Icon(
                  Icons.settings,
                  size: 11.5.sp,
                )
              ],
            ),
            onTap: () {
              handleClickFilter();
            },
          ),
        ],
      ),
    );
  }

  buildListItem(List list, int index, BuildContext ctx) {
    Map item = {
      'code': 'SERMO000188',
      'from': '桂林',
      'to': '香港',
      'product': '手机',
      'num': 5,
      'time': '2020-6-14 02:14:48',
    };
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top: 10.0.w),
      padding: EdgeInsets.symmetric(horizontal: 12.5.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(vertical: 15.0.w),
            child: Text(
              '单号${item['code']}',
              style: TextStyle(fontSize: 14.0.sp),
            ),
          ),
          Divider(
            height: 0.5,
            thickness: 0.5,
            color: ColorConstant.gray_cc,
          ),
          Padding(
              padding: EdgeInsets.symmetric(vertical: 15.0.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Text(
                        '${item['from']}',
                        style: TextStyle(fontSize: 14.0.sp),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 20.0.w),
                        child: Image.asset(
                          Constant.ASSETS_IMG + 'depart.png',
                          width: 15.w,
                          height: 5.5.h,
                        ),
                      ),
                      Text(
                        '${item['to']}',
                        style: TextStyle(fontSize: 14.0.sp),
                      ),
                    ],
                  ),
                  RoundButton(
                    width: 58.w,
                    height: 24.h,
                    text: '待确定',
                    style: TextStyle(fontSize: 12.sp, color: Colors.white),
                    bgColor: ColorConstant.purple,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular((24.h / 2)),
                        bottomLeft: Radius.circular((24.h / 2))),
                  )
                ],
              )),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '物品',
                style: TextStyle(
                    fontSize: 12.0.sp, color: ColorConstant.text_gray),
              ),
              Text(
                '${item['product']}',
                style: TextStyle(
                    fontSize: 12.0.sp, color: ColorConstant.text_gray),
              )
            ],
          ),
          Padding(
            padding: EdgeInsets.only(top: 12.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text(
                  '数量',
                  style: TextStyle(
                      fontSize: 12.0.sp, color: ColorConstant.text_gray),
                ),
                Text(
                  '${item['num']}',
                  style: TextStyle(
                      fontSize: 12.0.sp, color: ColorConstant.text_gray),
                )
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 13.0.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(right: 11.5.w),
                      child: Icon(
                        Icons.access_time,
                        size: 12.5.sp,
                      ),
                    ),
                    Text(
                      '${item['time']}',
                      style: TextStyle(fontSize: 14.0.sp),
                    )
                  ],
                ),
                RoundButton(
                  height: 40.h,
                  width: 63.w,
                  text: '收款码',
                  radius: 4.w,
                  style: TextStyle(fontSize: 14.0.sp, color: Colors.white),
                  onPressed: () {
                    handleClickBtn(2);
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget picAndTextButton(String text, String imgPath, Function callback) {
    return Container(
      width: 58.w,
      height: 24.h,
      decoration: BoxDecoration(
        color: Colors.white,
        image: DecorationImage(image: AssetImage(imgPath), fit: BoxFit.fill),
      ),
      alignment: Alignment.center,
      child: FlatButton(
        onPressed: callback,
        child: Text(text),
        color: Colors.transparent,
      ),
    );
  }

  handleClickFilter() {
    _scaffoldKey.currentState.openEndDrawer();
  }

  handleCloseDrawer() {
    print('handleCloseDrawer');
    Navigator.pop(context);
  }

  void resetFilter() {
    setState(() {
      _startDate = DateUtil.format(pattern: DateUtil.DATE_PATTERN);
      _endDate = DateUtil.format(pattern: DateUtil.DATE_PATTERN);
      _printStatus = '全部';
      _smsStatus = '全部';
    });
  }

  void handleClickBtn(int type) {
    Widget widget = buildContent(type);
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        builder: (BuildContext context) {
          return widget;
        });
  }

  Widget buildContent(int type) {
    Widget _child;
    Color _color = Colors.white;
    double _height;

    /// 收款码
    if (type == 1) {
      _height = 530.h;
      _child = buildQrCode();

      /// 确认价格
    }
    if (type == 2) {
      _height = 680.h;
      _color = ColorConstant.gray_f0;
      _child = buildConfirmPrice();
    }
    return SizedBox(
      height: _height,
      child: new Stack(
        children: <Widget>[
          Container(
            width: double.infinity,
            color: Colors.black54,
          ),
          Container(
            child: _child,
            decoration: BoxDecoration(
              color: _color,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(25),
                topRight: Radius.circular(25),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQrCode() {
    return Padding(
      padding: EdgeInsets.only(
          top: SizeConstants.marginSize.w,
          left: SizeConstants.marginSize.w,
          right: SizeConstants.marginSize.w),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Icon(Icons.data_usage),
              Padding(
                padding: EdgeInsets.only(left: SizeConstants.marginSize.w),
                child: Text('收款码'),
              )
            ],
          ),
          SizedBox(
            height: 16.0.h,
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 8.0.w, horizontal: 16.0.w),
            decoration: BoxDecoration(
                color: ColorConstant.gray_f0,
                borderRadius: BorderRadius.all(Radius.circular(18.w))),
            child: Text(
              '温馨提示：驿站出示此收款码收钱才有效',
              style: TextStyle(fontSize: 12.sp),
            ),
          ),
          SizedBox(
            height: 16.0.h,
          ),
          Container(
            color: ColorConstant.gray_f0,
            padding: EdgeInsets.all(16.0.w),
            child: QrImage(
              padding: EdgeInsets.zero,
              data: 'http://test.com',
              size: 180.0.w,
              errorStateBuilder: (cxt, err) {
                print('生成二维码错误 => ' + err);
                return Container(
                  child: Center(
                    child: Text(
                      "生成二维码错误",
                      textAlign: TextAlign.center,
                    ),
                  ),
                );
              },
            ),
          ),
          SizedBox(
            height: 24.0.h,
          ),
          RoundButton(
            text: '打印电子面单',
            style: TextStyle(color: Colors.white),
          )
        ],
      ),
    );
  }

  Widget buildConfirmPrice() {
    return Stack(
      children: <Widget>[
        Padding(
          padding: EdgeInsets.only(
              top: SizeConstants.marginSize.w,
              left: SizeConstants.marginSize.w,
              right: SizeConstants.marginSize.w),
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Icon(Icons.data_usage),
                  Padding(
                    padding: EdgeInsets.only(left: SizeConstants.marginSize.w),
                    child: Text('确认价格'),
                  )
                ],
              ),
              SizedBox(
                height: 16.0.h,
              ),
              buildListItem(null, null, null),
              SizedBox(
                height: 16.0.h,
              ),
              buildConfirmPriceItem(),
              SizedBox(
                height: 16.0.h,
              ),
            ],
          ),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                      border: Border(
                          top: BorderSide(
                              width: 0.5, color: ColorConstant.gray_f0))),
                  child: RoundButton(
                    text: '¥ 20.00',
                    style: TextStyle(fontSize: 15.sp),
                    radius: 0,
                    bgColor: Colors.white,
                    onPressed: () {
                      resetFilter();
                    },
                  ),
                ),
              ),
              Expanded(
                child: RoundButton(
                  text: '确定价格',
                  style: TextStyle(fontSize: 15.sp, color: Colors.white),
                  radius: 0,
                  bgColor: ColorConstant.app_main,
                  onPressed: () {},
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  buildConfirmPriceItem() {
    Map item = {
      'code': 'SERMO000188',
      'from': '桂林',
      'to': '香港',
      'product': '手机',
      'num': 5,
      'weight': 5,
      'actualWeight': 5,
      'time': '2020-6-14 02:14:48',
    };
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top: 10.0.w),
      padding: EdgeInsets.symmetric(horizontal: 12.5.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            height: 50.h,
            padding: EdgeInsets.symmetric(vertical: 8.0.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  '货品名称',
                  style: TextStyle(fontSize: 12.0.sp),
                ),
                Text(
                  '${item['product']}',
                  style: TextStyle(fontSize: 12.0.sp),
                )
              ],
            ),
          ),
          Divider(
            height: 0.5,
            thickness: 0.5,
            color: ColorConstant.gray_cc,
          ),
          Container(
            height: 50.h,
            padding: EdgeInsets.symmetric(vertical: 8.0.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  '数量',
                  style: TextStyle(fontSize: 12.0.sp),
                ),
                Text(
                  '${item['num']}',
                  style: TextStyle(fontSize: 12.0.sp),
                )
              ],
            ),
          ),
          Divider(
            height: 0.5,
            thickness: 0.5,
            color: ColorConstant.gray_cc,
          ),
          Container(
            height: 50.h,
            padding: EdgeInsets.symmetric(vertical: 8.0.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  '体积重量',
                  style: TextStyle(fontSize: 12.0.sp),
                ),
                NumberTextField(height: 26.h,iconWidth: 26.w,)
              ],
            ),
          ),
          Divider(
            height: 0.5,
            thickness: 0.5,
            color: ColorConstant.gray_cc,
          ),
          Container(
            height: 50.h,
            padding: EdgeInsets.symmetric(vertical: 8.0.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  '实际重量',
                  style: TextStyle(fontSize: 12.0.sp),
                ),
                NumberTextField(height: 26.h,iconWidth: 26.w,)
              ],
            ),
          ),
          Divider(
            height: 0.5,
            thickness: 0.5,
            color: ColorConstant.gray_cc,
          ),
          Container(
            height: 50.h,
            padding: EdgeInsets.symmetric(vertical: 8.0.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  '价格',
                  style: TextStyle(fontSize: 12.0.sp),
                ),
                Text(
                  '0元',
                  style: TextStyle(fontSize: 12.0.sp),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}
